package com.kd.juhaowan.ui.fragment;

import android.content.Intent;
import android.view.View;


import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.kd.juhaowan.R;
import com.kd.juhaowan.http.api.ReciveDjqApi;
import com.kd.juhaowan.http.model.GiftModel;
import com.kd.juhaowan.http.model.HttpData;
import com.kd.juhaowan.ui.GameDetailActivity;
import com.kd.juhaowan.ui.GameDetailActivity2;
import com.kd.juhaowan.ui.adapter.FuliDjqBannerPagerAdapter;
import com.kd.juhaowan.ui.dialog.ConfirmDialog;
import com.kd.juhaowan.ui.listener.OnReciveListener;
import com.kd.juhaowan.utils.DeviceUtil;
import com.kd.juhaowan.utils.LogUtil;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloader;
import com.youth.banner.Banner;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.indicator.CircleIndicator;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MoreDjqFragment extends BaseFragment implements OnReciveListener {

    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.fragment_moregift;
    }

    @BindView(R.id.mall_home_banner)
    Banner<String, FuliDjqBannerPagerAdapter> bannerView;

    private List<GiftModel> giftModels;
    private List<List<GiftModel>> datamodel=new ArrayList<>();
    private boolean isMine;

    @Override
    protected void reInitDate() {

    }

    @Override
    protected void onButterKnifeCreateViewAfter() {
        super.onButterKnifeCreateViewAfter();
        giftModels = (List<GiftModel>)getArguments().getSerializable("modle");
        isMine = getArguments().getBoolean("ismine",false);
        if(giftModels!=null&&giftModels.size()>0){
            int number = giftModels.size()/4+(giftModels.size()%4==0?0:1);
            LogUtil.debugLog(giftModels.size()+"..."+number);
            for(int i=0;i<number;i++){
                if(i==number-1){
                    datamodel.add(giftModels.subList(i*4,giftModels.size()));
                }else {
                    datamodel.add(giftModels.subList(i*4,i*4+4));
                }
            }
        }
        LogUtil.debugLog(datamodel.size()+"..."+isMine);
        bannerAdapter = new FuliDjqBannerPagerAdapter(datamodel,isMine,this);

        bannerView.setBannerRound2(UIUtil.dip2px(getContext(), 5));
        bannerView.setIndicator(new CircleIndicator(getContext()));
        bannerView.setIndicatorGravity(IndicatorConfig.Direction.CENTER);
        bannerView.setAdapter(bannerAdapter);


    }
    FuliDjqBannerPagerAdapter bannerAdapter;
    private ConfirmDialog dialog = null;
    @Override
    public void onGiftRecive(GiftModel model, boolean ismine,int paPosition) {
        LogUtil.debugLog(model.toString());
        if(ismine){
            if(DeviceUtil.isInstallApp(getContext(),model.getGame_package_name())){
                final Intent intent = getContext().getPackageManager().getLaunchIntentForPackage(model.getGame_package_name());
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                startActivity(intent);
            }else{
                Intent intent= new Intent(getActivity(), GameDetailActivity.class);
                intent.putExtra("id",model.getGame_id());
                intent.putExtra("startdownload",true);
                startActivity(intent);
            }
        }else {
            if (model.getIs_receive()==0){
                EasyHttp.post(this).api(new ReciveDjqApi(model.getId(),DeviceUtil.isInstallApp(getContext(),model.getGame_package_name())?1:2)).request(new HttpCallbackProxy<HttpData<GiftModel>>(this){
                    @Override
                    public void onHttpSuccess(HttpData<GiftModel> result, boolean cache) {
                        super.onHttpSuccess(result, cache);

                        List<GiftModel> models =datamodel.get(paPosition);
                        for (GiftModel mo:models) {
                            if(mo.getId().equals(model.getId())){
                                mo.setIs_receive(1);
                            }
                        }
                        datamodel.remove(paPosition);
                        datamodel.add(paPosition,models);
                        for (GiftModel mo:models) {
                            LogUtil.debugLog(mo.getIs_receive()+"..");
                        }
                        bannerAdapter.setDatas(datamodel);
                        bannerAdapter.notifyDataSetChanged();
//                        m648Adapter.notifyItemChanged(position,model);
                        startDownload(model);

                        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(getContext());
                        builder.setMessage(result.getMessage());
                        builder.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                onGiftRecive(model,true,paPosition);
                                dialog.dismiss();
                            }
                        });
                        dialog = builder.create();
                        dialog.show();

                    }

                    @Override
                    public void onHttpFail(Exception e) {
                        super.onHttpFail(e);
//                        List<GiftModel> models =datamodel.get(paPosition);
//                        for (GiftModel mo:models) {
//                            if(mo.getId().equals(model.getId())){
//                                mo.setIs_receive(1);
//                            }
//                        }
//                        datamodel.remove(paPosition);
//                        datamodel.add(paPosition,models);
//                        for (GiftModel mo:datamodel.get(paPosition)) {
//                            LogUtil.debugLog(mo.getIs_receive()+"..");
//                        }
//                        bannerAdapter.setDatas(datamodel);
//                        bannerAdapter.notifyDataSetChanged();
                    }
                });
            }else{

            }
        }
    }



    @Override
    public void onPause() {
        super.onPause();
        if(loadingid!=0){
            FileDownloader.getImpl().pause(loadingid);
        }
    }

    private int loadingid=0;

    private void startDownload(GiftModel model){
        StringBuilder builder = new StringBuilder(model.getGame_package_name().trim());
//        builder.append(gameid);
        builder.append(".apk");
        File file = new File(getContext().getExternalCacheDir(), builder.toString());
//        mSinglePath = FileDownloadUtils.getDefaultSaveRootPath()+
////                File.separator+"feifei_save"+
//                File.separator+model.getGame_package_name().trim()+".apk";;
        String mSinglePath = file.getAbsolutePath();
        BaseDownloadTask singleTask = FileDownloader.getImpl().create(model.getGame_urlfile())
//                .setPath(mSinglePath,false)
                .setPath(mSinglePath,false)
                .setCallbackProgressTimes(1000)
                .setMinIntervalUpdateSpeed(1000);
        loadingid = singleTask.start();

    }
}
